import requests
from typing import Dict, Any, Optional


def make_request(endpoint: str, token: str, method: str = 'GET', data: Optional[Dict] = None) -> Dict[Any, Any]:
    """
    通用的API请求函数

    Args:
        endpoint (str): API端点路径
        token (str): Cursor认证token
        method (str): HTTP请求方法 ('GET' 或 'POST')
        data (Dict, optional): POST请求的数据

    Returns:
        Dict: API响应的JSON数据

    Raises:
        requests.exceptions.RequestException: 当API请求失败时
    """
    base_url = "https://www.cursor.com/api"
    headers = {
        'Authorization': f'Bearer {token}',  # 修改认证方式
        'Content-Type': 'application/json'
    }

    url = f"{base_url}/{endpoint}"

    try:
        if method == 'GET':
            response = requests.get(url, headers=headers)
        else:
            response = requests.post(url, json=data or {}, headers=headers)

        if response.status_code == 401:
            print("认证失败：请检查token是否正确")

        response.raise_for_status()  # 检查响应状态
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"API请求失败: {str(e)}")
        raise


def query_usage(token: str) -> Dict[Any, Any]:
    """
    查询用户的使用情况

    Args:
        token (str): Cursor认证token

    Returns:
        Dict: 用户使用情况数据
    """
    return make_request("usage", token)


def query_monthly_data(token: str, month: int, year: int) -> Dict[Any, Any]:
    """
    查询指定月份的数据

    Args:
        token (str): Cursor认证token
        month (int): 月份 (1-12)
        year (int): 年份

    Returns:
        Dict: 月度数据
    """
    data = {
        "month": month,
        "year": year,
        "includeUsageEvents": False
    }
    return make_request("dashboard/get-monthly-invoice", token, "POST", data)


def query_usage_limit(token: str) -> Dict[Any, Any]:
    """
    查询使用限制

    Args:
        token (str): Cursor认证token

    Returns:
        Dict: 使用限制数据
    """
    return make_request("dashboard/get-hard-limit", token, "POST")


# 使用示例
if __name__ == "__main__":
    try:
        # token需要从VSCode插件中获取
        token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhdXRoMHx1c2VyXzAxSk1HUk1OR1ZKQzNaRDJGNkpDNllWSllFIiwidGltZSI6IjE3NDAwMjQ0ODciLCJyYW5kb21uZXNzIjoiNWJlMDU5MjItMWE4Yi00MTRlIiwiZXhwIjo0MzMyMDI0NDg3LCJpc3MiOiJodHRwczovL2F1dGhlbnRpY2F0aW9uLmN1cnNvci5zaCIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwgb2ZmbGluZV9hY2Nlc3MiLCJhdWQiOiJodHRwczovL2N1cnNvci5jb20ifQ.3ZTS_vHoAOPFxztfvc9M47070IHZAyUQsUFZm0HPEBA"

        # 查询使用情况
        usage_data = query_usage(token)
        print("Usage data:", usage_data)

        # 查询月度数据
        monthly_data = query_monthly_data(token, 12, 2023)
        print("Monthly data:", monthly_data)

        # 查询使用限制
        limit_data = query_usage_limit(token)
        print("Usage limit:", limit_data)

    except Exception as e:
        print(f"Error occurred: {str(e)}")
